import post from './http.js'
import * as storage from './storage.js'

function addOrder(order) {
	if (order) {
		let orders = storage.getIosOrders();
		if (!orders) orders = [];
		orders.push(order);
		storage.setIosOrders(orders);
	}
}

function removeOrder(order) {
	if (order) {
		let orders = storage.getIosOrders();
		if (orders) {
			for (let i = 0; i < orders.length; i++) {
				if (orders[i].orderId === order.orderId) {
					orders.splice(i, 1);
					break;
				}
			}
			if (orders.length > 0) {
				storage.setIosOrders(orders);
			} else {
				storage.setIosOrders(null);
			}
		}
	}
}

function postOrders() {
	let orders = storage.getIosOrders();
	if (orders) {
		let promises = [];
		for (let i = 0; i < orders.length; i++) {
			let order = orders[i];
			if (typeof order.orderString == "object") {
				order.orderString = JSON.stringify(order.orderString)
			}
			promises.push(post("pay/applePayBack", {
				orderId: order.orderId,
				orderString: order.orderString
			}).then(res => order));
		}
		Promise.allSettled(promises).then(res => {
			for (let item of res) {
				if (item.status === 'fulfilled') {
					removeOrder(item.value);
				}
			}
		});
	}
}

//检测苹果订单是否未提交
const checkOrderData = (orderData) => {
	if (!orderData) {
		orderData = storage.getIosOrder();
	}
	let orderId = [];
	let length = orderData.length;
	for (let i = 0; i < length; i++) {
		let order = orderData.pop();
		if (order.orderId && order.orderString) {
			let orderString = order.orderString;
			post("pay/applePayBack",{
				orderId: order.orderId,
				orderString: orderString
			}).then(ret => {
				if (orderData) {
					storage.setIosOrder(orderData);
				} else {
					storage.setIosOrder(null);
				}
			});
		}
	}
}

const postOrderData = (params = {}) => {
	post("pay/applePayBack", params).catch(err => {
		addOrder(params);
	});
}

export {
	addOrder,
	removeOrder,
	postOrders,
	postOrderData
}